const router = require('koa-router')();

const { login } = require('../model');

router.post('/string', async (ctx, next) => {
  ctx.body = 'koa2 string';
});
// 获取数据
router.post('/login/getAll', async (ctx, next) => {
  let res = await login.find();
  if (res) {
    ctx.body = {
      msg: '获取数据',
      code: 200,
      data: res,
    };
  }
});

// 注册账号
router.post('/register', async (ctx, next) => {
  const { username } = ctx.request.body;
  const res = await login.findOne({ username });
  if (res) {
    ctx.body = {
      code: 100,
      msg: '该账户已经注册，请更换其他账户',
      data: res,
    };
  } else {
    const res = await login.create({
      ...ctx.request.body,
      create_time: Date.now(),
      update_time: Date.now(),
    });

    ctx.body = {
      msg: '注册成功',
      code: 200,
      data: res,
    };
  }
});

//登录
router.post('/login', async (ctx, next) => {
  // 先验证是否存在账号
  const { username, password } = ctx.request.body;
  const res = await login.findOne({ username });
  if (res) {
    const ress = await login.findOne({ username, password });
    if (ress) {
      ctx.body = {
        code: 200,
        msg: '登录成功',
        data: ress,
      };
    } else {
      ctx.body = {
        code: 100,
        msg: '账号密码错误',
        data: ress,
      };
    }
  } else {
    ctx.body = {
      code: 300,
      msg: '该账户还未注册，请跳转到注册页进行注册',
      data: res,
    };
  }
});

module.exports = router;
